package com.cantor.consumer.tool;

import cn.hutool.core.lang.Console;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 负载统计工具
 * 维护一个队列和一个线程,队列塞任务,线程完成任务
 */
@Slf4j
public class StatQueueKeeper {

    // 要调用下面的startConsume方法之前,必须获取锁
    public static final Lock startLock = new ReentrantLock();

    // 任务队列
    public static final BlockingQueue<Runnable> statQueue = new LinkedBlockingQueue();

    public static final boolean isRunning = false;

    private StatQueueKeeper() {

    }

    // 这个方法只能被调用一次.
    public static void startConsume() {
        System.out.println("StatQueueKeeper开始工作...");
        if (isRunning) {
            return;
        }
        new Thread(() -> {
            while (true) {
                try {
                    statQueue.take().run();
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // private static void doIncrement(String path) {
    //     if (!countMap.containsKey(path)) {
    //         countMap.put(path, 1);
    //         return;
    //     }
    //     countMap.put(path, countMap.get(path) + 1);
    // }
    //
    // // 输出负载信息
    // public static void showStat(){
    //     countMap.forEach(Console::error);
    // }


}
